package com.zy.je.common.mybatis.ext.util;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.zy.je.common.core.model.LoginUser;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoginUserUtil {
    public static LoginUser getCurrentUser() {
        return LoginUser.builder()
                .id(getLoginIdWithNoExpt(String.class))
                .userName(getLoginExtraWithNoExpt("user_name", String.class))
                .clientId(getLoginExtraWithNoExpt("client_id", String.class))
                .build();
    }

    private static <T> T getLoginExtraWithNoExpt(String key, Class<T> cls) {
        try {
            Object o = StpUtil.getExtra(key);
            if (null != o) {
                return JSON.parseObject(JSON.toJSONString(o), cls);
            }
            return null;
        } catch (Throwable e) {
//            log.info(e.getMessage(), e);
            log.debug("未获取到登录信息", e.getMessage());
        }
        return null;
    }

    private static <T> T getLoginIdWithNoExpt(Class<T> cls) {
        try {
            Object o = StpUtil.getLoginId();
            if (null != o) {
                return JSON.parseObject(JSON.toJSONString(o), cls);
            }
            return null;
        } catch (Throwable e) {
//            log.info(e.getMessage(), e);
            log.debug("未获取到登录信息", e.getMessage());
        }
        return null;
    }
}
